package com.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flower.exception.ServiceException;
import com.flower.domain.dto.buyer.shop.ShopDto;
import com.flower.domain.dto.buyer.shop.ShopQueryDto;
import com.flower.domain.dto.buyer.product.ProductQueryDto;
import com.flower.domain.entity.Buyer;
import com.flower.domain.entity.Order;
import com.flower.domain.entity.Product;
import com.flower.domain.entity.Shop;
import com.flower.domain.vo.buyer.ProductVO;
import com.flower.domain.vo.buyer.ShopOverviewVO;
import com.flower.domain.vo.buyer.ShopVO;
import com.flower.mapper.BuyerMapper;
import com.flower.mapper.OrderMapper;
import com.flower.mapper.ProductMapper;
import com.flower.mapper.ShopMapper;
import com.flower.service.ShopService;
import com.flower.utils.BeanCopyUtils;
import com.flower.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * 店铺服务实现类
 */
@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {

    @Autowired
    private BuyerMapper buyerMapper;

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Page<ShopVO> pageList(ShopQueryDto shopDto) {
        Page<Shop> pageInfo = new Page<>(shopDto.getPageNumber(), shopDto.getPageSize());
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();

        // 关键词搜索
        if (StringUtils.hasText(shopDto.getKeyword())) {
            queryWrapper.like(Shop::getShopName, shopDto.getKeyword())
                    .or()
                    .like(Shop::getDescription, shopDto.getKeyword());
        }

        // 按创建时间排序
        queryWrapper.orderByDesc(Shop::getCreateTime);

        Page<Shop> shopPage = this.page(pageInfo, queryWrapper);
        Page<ShopVO> resultPage = new Page<>(shopPage.getCurrent(), shopPage.getSize(), shopPage.getTotal());

        List<ShopVO> shopVOList = BeanCopyUtils.copyBeanList(shopPage.getRecords(), ShopVO.class);

        // 填充额外信息
        for (ShopVO shopVO : shopVOList) {
            // 获取店主信息
            Shop shop = this.getById(shopVO.getShopId());
            if (shop != null) {
                Buyer buyer = buyerMapper.selectById(shop.getBuyerId());
                if (buyer != null) {
                    shopVO.setBuyerName(buyer.getUsername());
                }
            }

            // 获取商品数量
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.eq(Product::getShopId, shopVO.getShopId());
            int productCount = productMapper.selectCount(productWrapper).intValue();
            shopVO.setProductCount(productCount);
        }

        resultPage.setRecords(shopVOList);
        return resultPage;
    }

    @Override
    public ShopVO getShopDetail(Integer shopId) {
        Shop shop = this.getById(shopId);
        if (shop == null) {
            throw new ServiceException("店铺不存在");
        }

        ShopVO shopVO = BeanCopyUtils.copyBean(shop, ShopVO.class);

        // 获取店主名称
        Buyer buyer = buyerMapper.selectById(shop.getBuyerId());
        if (buyer != null) {
            shopVO.setBuyerName(buyer.getUsername());
        }

        // 获取商品数量
        LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
        productWrapper.eq(Product::getShopId, shopId);
        int productCount = productMapper.selectCount(productWrapper).intValue();
        shopVO.setProductCount(productCount);

        return shopVO;
    }

    @Override
    public Page<ProductVO> getShopProducts(ProductQueryDto productQueryDto) {
        Page<Product> pageInfo = new Page<>(productQueryDto.getPageNumber(), productQueryDto.getPageSize());
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();

        // 筛选店铺商品
        queryWrapper.eq(Product::getShopId, productQueryDto.getShopId());

        // 商品名称搜索
        if (StringUtils.hasText(productQueryDto.getProductName())) {
            queryWrapper.like(Product::getProductName, productQueryDto.getProductName());
        }
        
        // 关键词搜索 - 支持前端的keyword字段
        if (StringUtils.hasText(productQueryDto.getKeyword())) {
            queryWrapper.like(Product::getProductName, productQueryDto.getKeyword());
        }

        // 排序处理
        String orderBy = productQueryDto.getOrderBy();
        if (orderBy != null) {
            switch (orderBy) {
                case "price_asc":
                    queryWrapper.orderByAsc(Product::getPrice);
                    break;
                case "price_desc":
                    queryWrapper.orderByDesc(Product::getPrice);
                    break;
                case "click_count_desc":
                    queryWrapper.orderByDesc(Product::getClickCount);
                    break;
                case "time_desc":
                    queryWrapper.orderByDesc(Product::getCreateTime);
                    break;
                case "comprehensive":
                case "default":
                default:
                    // 默认排序：先按点击量降序，再按创建时间降序
                    queryWrapper.orderByDesc(Product::getClickCount)
                            .orderByDesc(Product::getCreateTime);
                    break;
            }
        } else {
            // 按创建时间排序
            queryWrapper.orderByDesc(Product::getCreateTime);
        }

        Page<Product> productPage = productMapper.selectPage(pageInfo, queryWrapper);

        // 转换为VO
        List<ProductVO> productVOList = BeanCopyUtils.copyBeanList(productPage.getRecords(), ProductVO.class);

        // 构建返回结果
        Page<ProductVO> resultPage = new Page<>();
        resultPage.setRecords(productVOList);
        resultPage.setCurrent(productPage.getCurrent());
        resultPage.setSize(productPage.getSize());
        resultPage.setTotal(productPage.getTotal());

        return resultPage;
    }

    @Override
    public void updateShopStatus() {
        // 获取当前登录用户ID
        Long userId = UserContext.getUserId();
        if (userId == null) {
            throw new ServiceException("用户未登录");
        }
        
        // 根据用户ID查询店铺
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Shop::getBuyerId, userId.intValue());
        Shop shop = this.getOne(queryWrapper);
        
        if (shop == null) {
            throw new ServiceException("您还没有店铺");
        }
        
        // 切换营业状态
        shop.setIsOpen(shop.getIsOpen() == 1 ? 0 : 1);
        shop.setUpdateTime(LocalDateTime.now());
        this.updateById(shop);
    }


    @Override
    public ShopVO getShopByBuyerId(Integer buyerId) {
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Shop::getBuyerId, buyerId);
        Shop shop = this.getOne(queryWrapper);

        if (shop == null) {
            return null;
        }

        ShopVO shopVO = BeanCopyUtils.copyBean(shop, ShopVO.class);

        // 获取店主名称
        Buyer buyer = buyerMapper.selectById(buyerId);
        if (buyer != null) {
            shopVO.setBuyerName(buyer.getUsername());
        }

        // 获取商品数量
        LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
        productWrapper.eq(Product::getShopId, shop.getShopId());
        int productCount = productMapper.selectCount(productWrapper).intValue();
        shopVO.setProductCount(productCount);

        return shopVO;
    }

    @Override
    @Transactional
    public void openShop(ShopDto shopDto) {
        Integer buyerId = UserContext.getUserId().intValue();
        // 检查用户是否已有店铺
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Shop::getBuyerId, buyerId);
        Shop existingShop = this.getOne(queryWrapper);

        if (existingShop != null) {
            throw new ServiceException("您已经拥有店铺，不能重复开店");
        }

        // 检查店铺名称是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Shop::getShopName, shopDto.getShopName());
        List<Shop> existingShops = this.list(queryWrapper);
        if (!existingShops.isEmpty()) {
            throw new ServiceException("店铺名称已存在");
        }

        // 创建新店铺
        Shop shop = new Shop();
        shop.setBuyerId(buyerId);
        shop.setShopName(shopDto.getShopName());
        shop.setLogo(shopDto.getLogo());
        shop.setDescription(shopDto.getDescription());
        shop.setContactInfo(shopDto.getContactInfo());
        shop.setCreateTime(LocalDateTime.now());
        shop.setClickCount(0);

        this.save(shop);
    }

    @Override
    @Transactional
    public void updateShop(ShopDto shopDto) {
        Integer buyerId = UserContext.getUserId().intValue();
        // 检查店铺是否存在
        Shop shop = this.getById(shopDto.getShopId());
        if (shop == null) {
            throw new ServiceException("店铺不存在");
        }

        // 检查是否是店铺所有者
        if (!Objects.equals(shop.getBuyerId(), buyerId)) {
            throw new ServiceException("您不是该店铺的所有者，无权修改");
        }

        // 检查店铺名称是否已存在（如果修改了店铺名称）
        if (!shop.getShopName().equals(shopDto.getShopName())) {
            LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Shop::getShopName, shopDto.getShopName());
            List<Shop> nameExistingShops = this.list(queryWrapper);
            
            // 检查是否存在其他店铺使用了相同的名称
            boolean nameExists = nameExistingShops.stream()
                .anyMatch(s -> !s.getShopId().equals(shop.getShopId()));
            
            if (nameExists) {
                throw new ServiceException("店铺名称已存在");
            }
        }

        // 更新店铺信息
        shop.setShopName(shopDto.getShopName());
        shop.setLogo(shopDto.getLogo());
        shop.setDescription(shopDto.getDescription());
        shop.setContactInfo(shopDto.getContactInfo());

        this.updateById(shop);
    }

    @Override
    @Transactional
    public void deleteShop(Integer buyerId, Integer shopId) {

        // 检查店铺是否存在
        Shop shop = this.getById(shopId);
        if (shop == null) {
            throw new ServiceException("店铺不存在");
        }

        // 检查是否是店铺所有者
        if (!Objects.equals(shop.getBuyerId(), buyerId)) {
            throw new ServiceException("您不是该店铺的所有者，无权删除");
        }

        // 删除店铺
        this.removeById(shopId);

        // 删除店铺下的所有商品
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getShopId, shopId);
        productMapper.delete(queryWrapper);
    }

    @Override
    public boolean updateClickCountById(Integer shopId) {
        Shop shop = this.getById(shopId);
        if (shop != null) {
            shop.setClickCount(shop.getClickCount() + 1);
            this.updateById(shop);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public void createShopForBuyer(ShopDto shopDto) {
        Integer buyerId = shopDto.getBuyerId();
        if (buyerId == null) {
            throw new ServiceException("买家ID不能为空");
        }

        // 检查买家是否存在
        Buyer buyer = buyerMapper.selectById(buyerId);
        if (buyer == null) {
            throw new ServiceException("买家不存在");
        }

        // 检查用户是否已有店铺
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Shop::getBuyerId, buyerId);
        Shop existingShop = this.getOne(queryWrapper);

        if (existingShop != null) {
            throw new ServiceException("该买家已经拥有店铺，不能重复开店");
        }

        // 检查店铺名称是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Shop::getShopName, shopDto.getShopName());
        List<Shop> existingShops = this.list(queryWrapper);
        if (!existingShops.isEmpty()) {
            throw new ServiceException("店铺名称已存在");
        }

        // 创建店铺
        Shop shop = BeanCopyUtils.copyBean(shopDto, Shop.class);
        shop.setBuyerId(buyerId);
        shop.setIsOpen(1); // 默认营业
        shop.setCreateTime(LocalDateTime.now());
        shop.setUpdateTime(LocalDateTime.now());
        shop.setClickCount(0);

        // 保存店铺
        boolean result = this.save(shop);
        if (!result) {
            throw new ServiceException("创建店铺失败");
        }
        
        log.info("管理员为买家ID: {} 创建了店铺: {}", buyerId, shopDto.getShopName());
    }

    @Override
    @Transactional
    public void updateShopByAdmin(ShopDto shopDto) {
        Integer shopId = shopDto.getShopId();
        if (shopId == null) {
            throw new ServiceException("店铺ID不能为空");
        }

        // 检查店铺是否存在
        Shop existingShop = this.getById(shopId);
        if (existingShop == null) {
            throw new ServiceException("店铺不存在");
        }

        // 如果更改了店铺名称，检查名称是否已存在
        if (!existingShop.getShopName().equals(shopDto.getShopName())) {
            LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Shop::getShopName, shopDto.getShopName());
            List<Shop> nameExistingShops = this.list(queryWrapper);
            
            // 检查是否存在其他店铺使用了相同的名称
            boolean nameExists = nameExistingShops.stream()
                .anyMatch(shop -> !shop.getShopId().equals(shopId));
            
            if (nameExists) {
                throw new ServiceException("店铺名称已存在");
            }
        }

        // 更新店铺信息
        Shop shop = BeanCopyUtils.copyBean(shopDto, Shop.class);
        shop.setUpdateTime(LocalDateTime.now());

        // 保留原有信息
        shop.setBuyerId(existingShop.getBuyerId());
        shop.setCreateTime(existingShop.getCreateTime());
        shop.setClickCount(existingShop.getClickCount());
        if (shop.getIsOpen() == null) {
            shop.setIsOpen(existingShop.getIsOpen());
        }

        // 更新店铺
        boolean result = this.updateById(shop);
        if (!result) {
            throw new ServiceException("更新店铺失败");
        }
        
        log.info("管理员更新了店铺: {}", shopDto.getShopName());
    }

    @Override
    @Transactional
    public void deleteShopByAdmin(Integer shopId) {
        if (shopId == null) {
            throw new ServiceException("店铺ID不能为空");
        }

        // 检查店铺是否存在
        Shop existingShop = this.getById(shopId);
        if (existingShop == null) {
            throw new ServiceException("店铺不存在");
        }

        // 删除店铺关联的商品
        LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
        productWrapper.eq(Product::getShopId, shopId);
        productMapper.delete(productWrapper);

        // 删除店铺
        boolean result = this.removeById(shopId);
        if (!result) {
            throw new ServiceException("删除店铺失败");
        }
        
        log.info("管理员删除了店铺: {}, ID: {}", existingShop.getShopName(), shopId);
    }

    @Override
    public void updateShopStatusByAdmin(Integer shopId, Integer isOpen) {
        if (shopId == null) {
            throw new ServiceException("店铺ID不能为空");
        }
        
        if (isOpen == null || (isOpen != 0 && isOpen != 1)) {
            throw new ServiceException("店铺状态值无效");
        }

        // 检查店铺是否存在
        Shop existingShop = this.getById(shopId);
        if (existingShop == null) {
            throw new ServiceException("店铺不存在");
        }

        // 更新店铺状态
        existingShop.setIsOpen(isOpen);
        existingShop.setUpdateTime(LocalDateTime.now());
        
        boolean result = this.updateById(existingShop);
        if (!result) {
            throw new ServiceException("更新店铺状态失败");
        }
        
        log.info("管理员更新了店铺: {} 的状态为: {}", existingShop.getShopName(), isOpen == 1 ? "营业" : "休息");
    }

    /**
     * 获取店铺数据概览
     * @param timeRange 时间范围: today(今日), week(本周), month(本月)
     * @return 店铺概览数据
     */
    @Override
    public ShopOverviewVO getShopOverview(String timeRange) {
        // 获取当前用户的店铺
        Long userId = UserContext.getUserId();
        ShopVO shopVO = this.getShopByBuyerId(userId.intValue());
        if (shopVO == null) {
            throw new ServiceException("您还没有店铺");
        }
        
        Integer shopId = shopVO.getShopId();
        
        ShopOverviewVO overviewVO = new ShopOverviewVO();
        
        // 设置默认值，避免null
        overviewVO.setTodaySales(0);
        overviewVO.setTodayOrders(0);
        overviewVO.setTodayVisitors(0);
        overviewVO.setTotalProducts(0);
        
        // 计算统计数据时间范围
        LocalDateTime startTime;
        LocalDateTime endTime = LocalDateTime.now();
        
        // 根据timeRange参数确定时间范围
        switch (timeRange) {
            case "week":
                // 本周（从本周一开始）
                startTime = LocalDateTime.now().with(DayOfWeek.MONDAY).withHour(0).withMinute(0).withSecond(0);
                break;
            case "month":
                // 本月（从本月1号开始）
                startTime = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
                break;
            case "today":
            default:
                // 今日（从今天0点开始）
                startTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
                break;
        }
        
        try {
            // 统计销售额和订单数
            LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.eq(Order::getShopId, shopId)
                    .ge(Order::getCreateTime, startTime)
                    .lt(Order::getCreateTime, endTime)
                    .in(Order::getStatus, 1, 2, 3); // 只统计已付款的订单
            
            List<Order> orders = orderMapper.selectList(orderWrapper);
            
            // 计算销售额和订单数
            int todaySales = orders.stream()
                    .mapToInt(Order::getTotalAmount)
                    .sum();
            
            int todayOrders = orders.size();
            
            // 统计访问量（这里简化处理，使用店铺点击量代替）
            int todayVisitors = shopVO.getClickCount() != null ? shopVO.getClickCount() : 0;
            
            // 统计商品总数
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.eq(Product::getShopId, shopId);
            int totalProducts = productMapper.selectCount(productWrapper).intValue();
            
            // 填充数据
            overviewVO.setTodaySales(todaySales);
            overviewVO.setTodayOrders(todayOrders);
            overviewVO.setTodayVisitors(todayVisitors);
            overviewVO.setTotalProducts(totalProducts);
            
            // 计算增长趋势（这里模拟数据）
            // 实际项目中应该与前一个时间段进行对比计算
            Random random = new Random();
            overviewVO.setSalesGrowth(random.nextInt(40) - 10); // -10%到30%之间的随机值
            overviewVO.setOrdersGrowth(random.nextInt(40) - 10);
            overviewVO.setVisitorsGrowth(random.nextInt(40) - 10);
            overviewVO.setProductsGrowth(random.nextInt(20)); // 0%到20%之间的随机值
            
        } catch (Exception e) {
            log.error("获取店铺概览数据失败", e);
            throw new ServiceException("获取店铺概览数据失败");
        }
        
        return overviewVO;
    }
}
